<template>
    <el-tabs v-model="activeTab" type="card">
        <!-- 离职申请 tab -->
        <el-tab-pane label="离职申请" name="resignApply">
            <el-card style="width: 90%;margin-bottom: 20px" shadow="always">
                <el-form ref="ruleFormRef" style="max-width: 600px;margin-left: 200px;background-color: beige;"
                    :model="resignForm" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize"
                    status-icon>
                    <!-- 姓名输入项 -->
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="resignForm.name" style="width: 150px;" placeholder="请输入你的姓名" clearable />
                    </el-form-item>
                    <!-- 性别选择项 -->
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="resignForm.gender" style="width: 150px;" placeholder="请选择" clearable>
                            <el-option label="男" value="1" />
                            <el-option label="女" value="2" />
                        </el-select>
                    </el-form-item>
                    <!-- 账号输入项 -->
                    <el-form-item label="账号" prop="account">
                        <el-input v-model="resignForm.account" style="width: 150px;" placeholder="请输入你的账号" clearable />
                    </el-form-item>
                    <!-- 申请日期选择项 -->
                    <el-form-item label="申请日期" prop="applyData">
                        <el-date-picker v-model="resignForm.applyDate" type="date" style="width: 150px;"
                            placeholder="请选择时间" clearable />
                    </el-form-item>
                    <!-- 申请文件上传项 -->
                    <el-form-item label="申请文件" prop="resignDocument">
                        <el-upload class="upload-demo" :on-success="handleAvatarSuccess"
                            :headers="getTokenForFileUpload" :show-file-list="false"
                            action="/api/emp/upload/file" 
                            :before-upload="beforeAvatarUpload">
                            <template #trigger>
                                <el-button type="primary">选择文件</el-button>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <!-- 申请原因输入项 -->
                    <el-form-item label="选择的文件" prop="file">
                        <div slot="tip">
                            <el-link :underline="false" :href="resignForm.resignDocument">{{ resignForm.resignDocument }}</el-link>
                        </div>
                    </el-form-item>
                    <!-- 提交和清空按钮 -->
                    <el-form-item style="margin-left: 200px;">
                        <el-button type="primary" @click="submitApplyResign">提交</el-button>
                        <el-button @click="clearResignForm">清空</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </el-tab-pane>
        <!-- 离职申请历史记录 tab -->
        <el-tab-pane label="离职申请历史记录" name="resignHistory">
            <el-card style="width: 90%;margin-top: 20px" shadow="always">
                <el-form :model="searchForm" :inline="true" style="margin-bottom: 10px">
                    <el-form-item label="审批状态">
                        <el-select v-model="searchForm.approveStatus" style="width: 100px;" placeholder="请选择">
                            <el-option label="审批中" value="0" />
                            <el-option label="通过" value="1" />
                            <el-option label="未通过" value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="申请日期">
                        <el-date-picker v-model="searchForm.applyDate" value-format="YYYY-MM-DD" type="daterange"
                            placeholder="选择日期范围" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="fetchResignData">查询</el-button>
                        <el-button type="info" @click="resetSearchForm">清空</el-button>
                    </el-form-item>
                </el-form>
                <el-table :data="filteredResignData" border style="width: 100%; margin-top: 10px;">
                    <el-table-column label="申请日期" prop="applyDate" />
                    <el-table-column label="申请文件" prop="resignDocument">
                        <template #default="scope">
                            <el-link :underline="false" :href="scope.row.resignDocument">{{ scope.row.resignDocument }}</el-link>
                        </template>
                    </el-table-column>
                    <el-table-column label="申请状态" prop="approveStatus">
                        <template #default="scope">
                            <span v-if="scope.row.approveStatus === 0">审批中</span>
                            <span v-if="scope.row.approveStatus === 1">通过</span>
                            <span v-if="scope.row.approveStatus === 2">未通过</span>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[5, 10, 15, 20]" :size="size" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </el-card>
        </el-tab-pane>
    </el-tabs>
    <!-- 修改密码的对话框 -->
    <el-dialog v-model="modifyDialogVisible" title="修改密码" width="500" draggable>
        <el-form ref="ruleFormRef" style="max-width: 400px" :model="ruleForm" :rules="modifyRules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <!-- 新密码输入项 -->
            <el-form-item label="新密码" prop="newPassword" placeholder="请输入新密码">
                <el-input v-model="ruleForm.newPassword" />
            </el-form-item>
            <!-- 再次输入新密码用于验证 -->
            <el-form-item label="再次输入新密码" prop="passwordCheck" placeholder="请再次输入新密码">
                <el-input v-model="ruleForm.passwordCheck" />
            </el-form-item>
            <!-- 确定修改密码按钮 -->
            <el-form-item>
                <el-button type="primary" @click="confirmPassword">确定</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import type { ComponentSize, FormInstance, FormRules, UploadProps } from 'element-plus';
import { ElMessage } from 'element-plus';
import axios from '@/utils/request';
import { empAccount } from '@/store';
import { getToken } from '@/utils/auth';
const activeTab = ref('resignApply');
// 用于控制表单尺寸，初始化为默认尺寸
const formSize = ref<ComponentSize>('default');
// 对表单实例的引用，用于后续验证、重置等操作
const ruleFormRef = ref<FormInstance>();
// 控制修改密码对话框的显示隐藏
const modifyDialogVisible = ref(false);
//获取用户名
const account = ref(empAccount().$state.account)
// 存储离职申请表单的数据，使用 ref 进行响应式包装
const resignForm = reactive({
    name: '',
    gender: '',
    resignDocument: '',
    applyDate: '',
    account: '',
});
resignForm.name = empAccount().$state.name
resignForm.gender = empAccount().$state.gender=='1'?'1':'2'
resignForm.account = empAccount().$state.account
const clearResignForm = () => {
    resignForm.name = '';
    resignForm.gender = '';
    resignForm.resignDocument = '';
    resignForm.applyDate = '';
};
// 离职申请表单的验证规则，使用 reactive 创建响应式对象
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '姓名不能为空', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '性别不能为空', trigger: 'change' }
    ],
    applyDate: [
        { required: true, message: '申请日期不能为空', trigger: 'change', type: 'date' }
    ],
    account: [
        { required: true, message: '账号不能为空', trigger: 'blur' }
    ],
    resignDocument: [
        { required: true, message: '申请文件不能为空', trigger: 'change' }
    ]
});
// 存储修改密码表单的数据，使用 reactive 创建响应式对象
const ruleForm = reactive({
    newPassword: '',
    passwordCheck: ''
});

// 修改密码表单的验证规则
const modifyRules = reactive<FormRules>({
    newPassword: [
        { min: 6, message: '密码长度必须大于六', trigger: 'blur' },
        { required: true, message: '请输入新密码', trigger: 'blur' },
    ],
    passwordCheck: [
        { min: 6, message: '密码长度必须大于六', trigger: 'blur' },
        { required: true, message: '请输入新密码', trigger: 'blur' },
        {
            validator: (value, callback) => {
                // 验证两次输入的密码是否一致
                if (value !== ruleForm.newPassword) {
                    callback(new Error('两次密码输入的不一致'));
                } else {
                    callback();
                }
            }, trigger: 'blur'
        }
    ]
});

// 提交离职申请表单的函数，进行表单验证并根据结果执行相应操作

// 重置离职申请表单的函数，清除表单数据并重置相关状态
// 上传文件前的钩子函数，用于验证文件类型和大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
    const allowedDocTypes = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
    const isDoc = allowedDocTypes.includes(file.type);
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isDoc) {
        ElMessage.error('上传的文件必须是新版docx格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传的文件大小不能超过2MB!');
    }
    return isDoc && isLt2M;
};

// 确认修改密码的函数，简单验证新密码是否输入后给出相应提示
const confirmPassword = () => {
    if (ruleForm.newPassword && ruleForm.passwordCheck) {
        ElMessage.success('修改成功');
        // 此处可以添加实际的修改密码到后端的逻辑，比如发送 axios 请求等
    } else {
        ElMessage.error('修改失败');
    }
};

// 离职申请历史记录相关
const searchForm = reactive({
    approveStatus: '',
    applyDate: ['', '']
});
const currentPage = ref(1);
const pageSize = ref(10);
const size = ref<ComponentSize>('default');
const background = ref(true);
const disabled = ref(false);
const total = ref(0);
const filteredResignData = ref([]);

// 分页尺寸改变时的处理函数
const handleSizeChange = (size: number) => {
    pageSize.value = size;
    fetchResignData();
};

// 当前页码改变时的处理函数
const handleCurrentChange = (page: number) => {
    currentPage.value = page;
    fetchResignData();
};
//获取请求头
const getTokenForFileUpload = reactive({
    token: getToken()
})
// 获取离职申请历史记录数据的函数，从后端接口获取数据
const fetchResignData = async () => {
    try {
        const response = await axios.get('/emp/resign', {
            params: {
                page: currentPage.value,
                pageSize: pageSize.value,
                approveStatus: searchForm.approveStatus,
                account: account.value,
                startDate: searchForm.applyDate[0],
                endDate: searchForm.applyDate[1]
            }
        });
        if (response.data.code === 1) {
            filteredResignData.value = response.data.data.rows;
            total.value = response.data.data.total;
            // 查询成功判断
            if(searchForm.approveStatus !== '' || searchForm.applyDate[0]!== '' || searchForm.applyDate[1]!== ''){
                ElMessage({
                    message: '查询成功！',
                    type: 'success',
                    duration: 2000
                });
            }
        } else {
            ElMessage({
                message: '获取离职申请记录失败！',
                type: 'error',
                duration: 2000
            });
        }
    } catch (error) {
        console.error(error);
        ElMessage({
            message: '网络错误，请检查网络连接或联系管理员！',
            type: 'error',
            duration: 2000
        });
    }
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    resignForm.resignDocument = response.data;
};

const resetSearchForm = () => {
    searchForm.approveStatus = '';
    searchForm.applyDate = ['', ''];
    fetchResignData();
}
//申请离职
const submitApplyResign = async () => {
    try {
        const response = await axios.post('/emp/resign', resignForm);
        if (response.data.code === 1) {
            ElMessage.success('申请离职成功！');
            // 重置表单
            clearResignForm();
            // 刷新数据
            fetchResignData();
            //跳转到离职申请历史记录页面
            activeTab.value = 'resignHistory';
        } else {
            ElMessage.error('申请离职失败！信息要填写完整');
        }
    } catch (error) {
        ElMessage.error('申请离职失败！');
    }
};
onMounted(() => {
    fetchResignData();
});

</script>

<style scoped>
.el-table {
    border-collapse: collapse;
    border-spacing: 0;
    width: 100%;
    margin-top: 20px;
    background-color: #fff;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
}

.el-table th {
    background-color: #f0f0f0;
    border-bottom: 1px solid #ddd;
    padding: 10px 15px;
    text-align: center;
    font-weight: bold;
}

.el-table td {
    border-bottom: 1px solid #ddd;
    padding: 10px 15px;
    text-align: center;
}

.el-table tr:hover {
    background-color: #fafafa;
}

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    padding: 20px;
}

.form-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.form-label {
    width: 80px;
    margin-right: 10px;
    color: #333;
}

.input-focused {
    border-color: #409EFF !important;
    box-shadow: 0 0 5px rgba(64, 158, 255, 0.5) !important;
}

.button-group {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.demo-form-inline {
    display: flex;
    align-items: center;
    justify-content: center;
}

.el-tabs {
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    background-color: white;
    padding: 20px;
}

.el-tabs__item {
    padding: 10px 20px;
    font-size: 16px;
    color: #333;
}

.el-button {
    border-radius: 4px;
    transition: all 0.3s ease;
}

.el-button:hover {
    opacity: 0.8;
}

.el-table {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    overflow: hidden;
    margin-top: 10px;
}

.el-table th,
.el-table td {
    padding: 8px 10px;
    text-align: center;
}

.el-pagination {
    margin-top: 10px;
    text-align: right;
}
</style>
